<template>
  <div class="shelf-footer" v-show="isEditMode">
    <div class="shelf-footer-tab-wrapper"
         v-for="item of tab"
         :key="item.index"
         @click="onTabClick(item)">
      <div class="shelf-footer-tab" :class="{'is-selected': isSelected}">
        <div class="iconfont tab-icon" v-if="item.index === 1">{{isPrivate ? '&#xe606;' : '&#xe603;'}}</div>
        <div class="iconfont tab-icon" v-if="item.index === 2">{{isDownload ? '&#xe611;' : '&#xe61c;'}}</div>
        <div class="iconfont tab-icon" v-if="item.index === 3">&#xe601;</div>
        <div class="iconfont tab-icon icon-shelf" v-if="item.index === 4">&#xe609;</div>
        <div class="tab-text" :class="{'remove-text': item.index === 4}">{{label(item)}}</div>
      </div>
    </div>
  </div>
</template>

<script>
import { storeShelfMixin } from '../../utils/mixin'
import { removeLocalStorage, saveBookShelf } from '../../utils/localStroage'
import { download } from '../../api/store'
import { removeLocalForage } from '../../utils/localForage'

export default {
  name: 'ShelfFooter',
  mixins: [storeShelfMixin],
  computed: {
    isSelected () {
      return this.shelfSelected && this.shelfSelected.length > 0
    },
    tab () {
      return [
        {
          label: this.$t('shelf.private'),
          label2: this.$t('shelf.noPrivate'),
          index: 1
        },
        {
          label: this.$t('shelf.download'),
          label2: this.$t('shelf.delete'),
          index: 2
        },
        {
          label: this.$t('shelf.move'),
          index: 3
        },
        {
          label: this.$t('shelf.remove'),
          index: 4
        }
      ]
    },
    isPrivate () {
      if (!this.isSelected) {
        return false
      } else {
        // 遍历每本书,每本书都是true，才会返回private的状态
        return this.shelfSelected.every(item => item.private)
      }
    },
    isDownload () {
      if (!this.isSelected) {
        return false
      } else {
        return this.shelfSelected.every(item => item.cache)
      }
    }
  },
  data () {
    return {
      popupMenu: null
    }
  },
  methods: {
    async downloadSelectedBook () {
      for (let i = 0; i < this.shelfSelected.length; i++) {
        await this.downloadBook(this.shelfSelected[i]).then(book => {
          book.cache = true
        })
      }
    },
    downloadBook (book) {
      let text = ''
      const toast = this.toast({
        text
      })
      // 一直展示
      toast.continueShow()
      return new Promise((resolve, reject) => {
        download(book, book => {
          toast.remove()
          resolve(book)
        }, reject, progressEvent => {
          // 解决下载速度快text为NULL的情况，
          if (progressEvent && progressEvent.loaded && progressEvent.total) {
            const progress = Math.floor(progressEvent.loaded / progressEvent.total * 100) + '%'
            text = this.$t('shelf.progressDownload').replace('$1', `${book.fileName}.epub(${progress})`)
            toast.updateText(text)
          }
        })
      })
    },
    removeSelectedBook () {
      // 一次性删除
      Promise.all(this.shelfSelected.map(book => this.removeBook(book))).then(books => {
        books.map(book => {
          // 将书本修改为还没被缓存
          book.cache = false
        })
        saveBookShelf(this.shelfList)
        this.simpleToast(this.$t('shelf.removeDownloadSuccess'))
      })
    },
    removeBook (book) {
      return new Promise((resolve, reject) => {
        removeLocalStorage(`${book.categoryText}/${book.fileName}-info`)
        removeLocalForage(`${book.fileName}`)
        // 成功执行完毕后返回一个Promise对象继续执行
        resolve(book)
      })
    },
    label (item) {
      switch (item.index) {
        case 1:
          return this.isPrivate ? item.label2 : item.label
        case 2:
          return this.isDownload ? item.label2 : item.label
        default:
          return item.label
      }
    },
    hidePopup () {
      this.popupMenu.hide()
    },
    // 保存书架
    onComplete () {
      this.hidePopup()
      this.setIsEditMode(false)
      // shelfSelected是从shelfList中引用，所有会跟着变化
      saveBookShelf(this.shelfList)
    },
    setPrivate () {
      let isPrivate
      if (this.isPrivate) {
        // 当全部都是private时候,设置为private
        isPrivate = false
      } else {
        isPrivate = true
      }
      this.shelfSelected.forEach(book => {
        // 覆盖其书本的所有Private值
        book.private = isPrivate
      })
      this.onComplete()
      if (isPrivate) {
        this.simpleToast(this.$t('shelf.setPrivateSuccess'))
      } else {
        this.simpleToast(this.$t('shelf.closePrivateSuccess'))
      }
    },
    async setDownload () {
      // 下载选择的电子书
      this.onComplete()
      if (this.isDownload) {
        this.removeSelectedBook()
      } else {
        await this.downloadSelectedBook() // 虽然里面是异步的，但是会等里面执行完，才继续执行
        saveBookShelf(this.shelfList)
        // download是异步，toast是同步，所有需要使用async和await，将其改为同步执行
        this.simpleToast(this.$t('shelf.setDownloadSuccess'))
      }
    },
    removeSelected () {
      this.shelfSelected.forEach(selected => {
        // 筛选不是选择的书本，重新构成一个新数组，成为书架的内容
        this.setShelfList(this.shelfList.filter(book => book !== selected))
      })
      this.setShelfSelected([])
      this.onComplete() // 保存书架
    },
    showPrivate () {
      this.popupMenu = this.popup({
        title: this.isPrivate ? this.$t('shelf.closePrivateTitle') : this.$t('shelf.setPrivateTitle'),
        btn: [
          {
            text: this.isPrivate ? this.$t('shelf.close') : this.$t('shelf.open'),
            click: () => {
              this.setPrivate()
            }
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup()
            }
          }
        ]
      }).show()
    },
    showDownload () {
      this.popupMenu = this.popup({
        title: this.isDownload ? this.$t('shelf.removeDownloadTitle') : this.$t('shelf.setDownloadTitle'),
        btn: [
          {
            text: this.isDownload ? this.$t('shelf.delete') : this.$t('shelf.open'),
            click: () => {
              this.setDownload()
            }
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup()
            }
          }
        ]
      }).show()
    },
    showRemove () {
      let title
      if (this.shelfSelected.length === 1) {
        title = this.$t('shelf.removeBookTitle').replace('$1', `《${this.shelfSelected[0].title}》`)
      } else {
        title = this.$t('shelf.removeBookTitle').replace('$1', this.$t('shelf.selectedBooks'))
      }
      this.popupMenu = this.popup({
        title: title,
        btn: [
          {
            text: this.$t('shelf.removeBook'),
            type: 'danger',
            click: () => {
              this.removeSelected()
            }
          },
          {
            text: this.$t('shelf.cancel'),
            click: () => {
              this.hidePopup()
            }
          }
        ]
      }).show()
    },
    onTabClick (item) {
      if (!this.isSelected) {
        return
      }
      switch (item.index) {
        case 1:
          this.showPrivate()
          break
        case 2:
          this.showDownload()
          break
        case 3:
          this.dialog().show()
          break
        case 4:
          this.showRemove()
          break
        default:
          // 几种情况之外不处理，防止BUG
          break
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
  @import '../../assets/styles/global.styl'
  .shelf-footer
    position: fixed
    bottom: 0
    left: 0
    z-index: 120
    display: flex
    width: 100%
    height: px2rem(48)
    background: white
    box-shadow: 0 px2rem(-2) px2rem(4) 0 rgba(0, 0, 0, .1)
    .shelf-footer-tab-wrapper
      flex: 1
      width: 25%
      height: 100%
      .shelf-footer-tab
        width: 100%
        height: 100%
        opacity: .5
        columnCenter()
        &.is-selected
          opacity: 1
        .tab-icon
          font-size: px2rem(20)
          color: #666
        .tab-text
          margin-top: px2rem(5)
          font-size: px2rem(12)
          color: #666
          &.remove-text
            color: $color-pink
        .icon-shelf
          color: $color-pink
</style>
